package com.jxbeidou.login.listener;

import com.jxbeidou.core.entity.SecurityUserVO;
import com.jxbeidou.core.ip2region.config.Ip2RegionBean;
import com.jxbeidou.login.event.LoginFailedEvent;
import com.jxbeidou.login.event.LoginSuccessEvent;
import com.jxbeidou.login.event.LogoutSuccessEvent;
import com.jxbeidou.system.api.log.LoginLogAPI;
import com.jxbeidou.system.api.log.vo.LogLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import jakarta.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @program: jxbeidou-basic
 * @ClassName: UserLoginListener
 * @description: 用户登录登出监听
 * @author: 杜晓祥
 * @create: 2023-12-26 17:08
 * 版权所有：交信北斗(北京)信息科技有些公司
 */

@Component
@Slf4j
public class UserLoginListener {

    @Resource
    private LoginLogAPI loginLogAPI;

    @Resource
    private Ip2RegionBean ip2RegionBean;

    @EventListener({LoginSuccessEvent.class})
    public void loginSuccessEvent (LoginSuccessEvent loginSuccessEvent) {
        log.debug("用户登录成功，记录登录操作日志开始");
        SecurityUserVO user = loginSuccessEvent.getUser();
        LogLoginVO logLoginVO = new LogLoginVO();
        logLoginVO.setUsername(user.getUsername());
        logLoginVO.setAddress(ip2RegionBean.searchIsp(loginSuccessEvent.getIp()));
        logLoginVO.setIp(loginSuccessEvent.getIp());
        logLoginVO.setOperation(0);
        logLoginVO.setStatus(1);
        logLoginVO.setCreateTime(LocalDateTime.now());
        loginLogAPI.save(logLoginVO);
        log.debug("用户登录成功，记录登录操作日志结束");
    }

    @EventListener({LoginFailedEvent.class})
    public void loginFailedEvent (LoginFailedEvent loginFailedEvent) {
        log.debug("用户登录失败，记录登录操作日志开始");
        SecurityUserVO user = loginFailedEvent.getUser();
        LogLoginVO logLoginVO = new LogLoginVO();
        logLoginVO.setUsername(user.getUsername());
        logLoginVO.setAddress(ip2RegionBean.searchIsp(loginFailedEvent.getIp()));
        logLoginVO.setIp(loginFailedEvent.getIp());
        logLoginVO.setOperation(4);
        logLoginVO.setStatus(0);
        logLoginVO.setCreateTime(LocalDateTime.now());
        loginLogAPI.save(logLoginVO);
        log.debug("用户登录失败，记录登录操作日志结束");
    }

    @EventListener({LogoutSuccessEvent.class})
    public void logoutSuccessEvent (LogoutSuccessEvent logoutSuccessEvent) {
        log.debug("用户登出成功，记录登录操作日志开始");
        SecurityUserVO user = logoutSuccessEvent.getUser();
        LogLoginVO logLoginVO = new LogLoginVO();
        logLoginVO.setUsername(user.getUsername());
        logLoginVO.setAddress(ip2RegionBean.searchIsp(logoutSuccessEvent.getIp()));
        logLoginVO.setIp(logoutSuccessEvent.getIp());
        logLoginVO.setOperation(1);
        logLoginVO.setStatus(1);
        logLoginVO.setCreateTime(LocalDateTime.now());
        loginLogAPI.save(logLoginVO);
        log.debug("用户登出成功，记录登录操作日志结束");
    }

}
